import React, { Component } from 'react';
import {
	StyleSheet, Text, Modal,
	PixelRatio, View, Image, ScrollView
} from "react-native";
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { API, API_GENERATE } from '../../../../config/api';
import HTTP from '../../../../utils/http';
import Utils from '../../../../utils/utils';
import MethodUtil from '../../../../utils/MethodUtil';
import navigationSeevice from '../../../../components/navigation/navigationSeevice';

const scale = GLOBAL.SCALE;

export class RelevanceDetailContainer extends Component {
	constructor(props) {
		super(props);
		console.log('props-传参数', props);
		this.state = {
			orderTotalQuantity: 0,
			totalPlanGrossProfit: 0,
			orderMappingInfo: [],
			totalMappingProfit: 0,
			orderTotalMapping: 0,
			pbocPrice: 0,
		}
	}

	componentWillMount() {
		this._init();
		this._getOrderMapping();
	}

	_init() {
		let orderTotalQuantity = 0; //订单总量
		let totalPlanGrossProfit = 0; //订单总额
		let { resultData } = this.props || {};
		let { orderItemList } = resultData || {};
		orderItemList && orderItemList.length && orderItemList.map((item, index) => {
			orderTotalQuantity = orderTotalQuantity + parseFloat(item.quantity || 0);
			totalPlanGrossProfit = totalPlanGrossProfit + MethodUtil.countObj.multiply(item.nakedPrice, item.quantity, 2);
		})
		this.setState({
			orderTotalQuantity,
			totalPlanGrossProfit
		})
	}

	_getOrderMapping = async () => {
		let totalMappingProfit = 0;
		let orderTotalMapping = 0;
		let pbocPrice = 0; //汇率
		let { resultData } = this.props || {};
		let { SOrderInfo, orderItemList } = resultData || {};
		let { orderId, companyName } = SOrderInfo || {};
		let response = await HTTP.POST(API_GENERATE(API.ZXY_USED_MAPPING_LIST), { orderId, isLast: 0 });
		if (!response || !response.length) {
			response = [];
			orderItemList && orderItemList.length && orderItemList.map((item, index) => {
				response[index] = {};
				response[index]['groupName'] = item.goodsName;
				response[index]['availableQuantity'] = item.quantity;
				response[index]['orderInfo'] = {};
				response[index]['orderInfo']['goodsId'] = item.goodsId;
				response[index]['orderInfo']['batchNo'] = item.batchNo;
				response[index]['orderInfo']['orderId'] = orderId;
				response[index]['orderInfo']['companyName'] = companyName;
			})
		} else {
			//计算合计利润
			response.map((item, index) => {
				let quantity = 0;
				let expectALl = 0; //总毛利
				let average = this._average(item.stockMappingList) || 0; // 均价
				item.expect = parseFloat(item.orderInfo.originPrice || 0) - average;//差价
				pbocPrice = item.orderInfo.pbocPrice; //汇率
				item.stockMappingList && item.stockMappingList.map(async (mapping, i) => {
					const { lockedTO } = mapping;
					// 单商品总关联数量
					quantity = quantity + lockedTO.lockedQuantity;
					item.lockedQuantity = quantity;
					// 单关联毛利
					mapping.expectSingle = MethodUtil.countObj.multiply(item.expect, (lockedTO.lockedQuantity || 0), 2);
					// 单商品总毛利
					expectALl = MethodUtil.countObj.add(expectALl, mapping.expectSingle, 2)
				})

				orderItemList && orderItemList.length && orderItemList.map((proItem, index) => {
					if (proItem.goodsId === item.orderInfo.goodsId) {
						//单商品总（待关）量
						item.totalQuantity = proItem.quantity || 0;
						// 单商品总待关联量=单商品总量-单商品已关联量
						item.availableQuantity = (proItem.quantity || 0) - (item.lockedQuantity || 0);
					}
				})
				// 订单总毛利
				totalMappingProfit = totalMappingProfit + (expectALl || 0);
				// 毛利计算规则展示该订单总关联量
				orderTotalMapping = orderTotalMapping + (item.lockedQuantity || 0);
				// 均价
				item.average = average;
				// 总毛利
				item.expectALl = expectALl;
			})
		}

		console.log('response-完结了', response)
		this.setState({
			orderMappingInfo: response,
			totalMappingProfit,
			orderTotalMapping,
			pbocPrice
		})
	}

	//均价
	_average = (sendData) => {  // 均价 = (关联总价格 / 关联总数量 )   关联总价格 = 多个关联累加(关联价格*关联数量)
		let tolPrice = 0;
		let tolQuantity = 0;
		sendData && sendData.forEach(item => {
			const { lockedTO, orderInfo } = item;
			tolQuantity = tolQuantity + lockedTO.lockedQuantity; //多个已关联总量
			tolPrice = tolPrice + (orderInfo.originPrice || 0) * (lockedTO.lockedQuantity || 0);  //多个已关联总价
		})
		if (tolQuantity) {
			return MethodUtil.countObj.divide(tolPrice, tolQuantity, 2) || 0;
		} else {
			return 0
		}
	}

	//采购成交
	_sellView = () => {
		const { orderMappingInfo, orderTotalMapping, orderTotalQuantity, totalMappingProfit, totalPlanGrossProfit, pbocPrice } = this.state;
		let rnbProfit = MethodUtil.countObj.multiply(totalMappingProfit, pbocPrice, 2);
		let rnbAmt = MethodUtil.countObj.multiply(totalPlanGrossProfit, pbocPrice, 2);
		return (
			<View>
				<View style={styles.top}>
					<Text style={styles.topTitle}>合计:</Text>
					<Text style={styles.topText}>总量 {orderTotalQuantity || '-'} 吨，总额：$ {MethodUtil.toThousands(totalPlanGrossProfit || 0, 2) || '-'}美元（折合人民币：¥{MethodUtil.toThousands(rnbAmt || 0, 2)}元）</Text>
					<Text style={styles.topText}>关联总量{orderTotalMapping || '-'}吨，<Text style={{ color: '#E02020' }}>总毛利{MethodUtil.toThousands(totalMappingProfit || 0, 2) || '-'}美元（折合人民币：¥{MethodUtil.toThousands(rnbProfit || 0, 2)}元）</Text></Text>
				</View>
				{
					orderMappingInfo && orderMappingInfo.length ?
						orderMappingInfo.map((orderMapping, index) => {
							let { groupName, orderInfo, stockMappingList, lockedQuantity, availableQuantity, totalQuantity,
								average, expectALl, expect } = orderMapping;

							return (
								<View key={index} style={styles.itemBox}>
									<View style={[styles.head, styles.xian]}>
										<View style={[styles.rowbt, styles.ptop]}>
											<Text style={styles.bold}>{groupName ? (groupName.length > 20 ? groupName.substr(0, 20) + "..." : groupName) : ""}</Text>
											<Text style={styles.bold}><Text style={styles.fontSize16}>$ {average || '-'}</Text>/吨</Text>
										</View>
										<View style={styles.rowbt}>
											<View style={styles.rowItem}>
												<Text style={styles.norl}>已关联</Text>
												<Text style={styles.bold}><Text style={styles.fontSize16}>{parseFloat(lockedQuantity || 0).toFixed(3) || 0}</Text> 吨</Text>
											</View>
											<View style={styles.rowItem}>
												<Text style={styles.norl}>待关联</Text>
												<Text style={styles.bold}><Text style={styles.fontSize16}>{parseFloat(availableQuantity || 0).toFixed(3) || 0}</Text> 吨</Text>
											</View>
											<View style={styles.rowItem}>
												<Text style={styles.norl}>总毛利</Text>
												<Text style={[styles.bold, styles.ctInputTextRed]}><Text style={styles.fontSize16}>{MethodUtil.toThousands(expectALl || 0, 2) || 0}</Text> 美元</Text>
											</View>
										</View>
									</View>
									{
										stockMappingList && stockMappingList.length ?
											stockMappingList.map((item, i) => {
												const { lockedTO, orderInfo } = item || {};
												const { lockedQuantity, availableQuantity } = lockedTO || {};
												const { companyName, orderId, originPrice } = orderInfo || {};
												return (
													<View key={i} style={styles.contian}>
														<Text style={styles.ctTitle}>{companyName && companyName.length > 20 ? companyName.substr(0, 20) + "..." : (companyName || '-')} | <Text style={{ color: style.color.themeColor }} onPress={() => { navigationSeevice.navigate('') }}>{orderId || '-'}</Text></Text>
														<View style={styles.ctInputBox}>
															<Text style={styles.money}>{lockedQuantity || '-'}吨 | </Text>
															<Text style={styles.money}>$ {originPrice || '-'}/吨 | </Text>
															{
																Utils.isEmpty(availableQuantity) ? null : <Text style={styles.money}>可关{availableQuantity}吨 | </Text>
															}
															<Text style={styles.money}>毛利：<Text style={styles.ctInputTextRed}>{MethodUtil.toThousands(item.expectSingle || 0, 2) || '-'}美元</Text></Text>
														</View>
													</View>
												)
											}) : <View style={styles.emptyView}>
												<Text style={styles.emptyText}>该商品无关联信息</Text>
											</View>
									}
								</View>
							)
						}) : null
				}
			</View>
		)
	}

	render() {
		const { isDetail } = this.props;
		return (
			<View style={styles.container}>
				<ScrollView style={{ marginBottom: isDetail ? 0 : 80 * scale }}>
					{this._sellView()}
				</ScrollView>
			</View>
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: '#fff',
	},
	top: {
		width: '100%',
		flexDirection: 'column',
		alignItems: "flex-start",
		justifyContent: 'center',
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale
	},
	topTitle: {
		fontSize: 13 * scale,
		fontWeight: 'bold',
		marginTop: 12 * scale
	},
	topText: {
		fontSize: 11 * scale,
		marginTop: 12 * scale
	},
	xian: {
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
	},
	itemBox: {
		width: '100%',
		borderRadius: 4 * scale,
		// marginBottom: 10 * scale
	},
	head: {
		backgroundColor: '#F4F7FE',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
		position: 'relative',
		padding: 12 * scale,
		marginTop: 15 * scale
	},
	contian: {
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
		position: 'relative'
	},
	ctTitle: {
		fontSize: 12 * scale,
		marginLeft: 15 * scale
	},
	money: {
		fontWeight: 'bold',
		fontSize: 12 * scale
	},
	emptyView: {
		width: '100%',
		borderTopWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderTopColor: style.color.gray,
		paddingTop: 25 * scale,
		paddingBottom: 20 * scale,
		alignItems: 'center'
	},
	ctInputBox: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		paddingLeft: 15 * scale
	},
	ctInputTextRed: {
		color: style.color.lightRed
	},
	rowbt: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between'
	},
	rowItem: { flex: 1 },
	ptop: {
		marginBottom: 15 * scale
	},
	norl: {
		color: '#333',
		fontSize: 13 * scale,
		paddingBottom: 5 * scale
	},
	bold: {
		fontSize: 13 * scale,
		fontWeight: 'bold',
		color: '#060606'
	},
	colorRed: {
		fontSize: 13 * scale,
		color: '#E02020'
	},
	themeColor: {
		color: style.color.themeColor,
		fontSize: 11 * scale
	},
	fontSize16: {
		fontSize: 16 * scale
	}
})